/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.ui;

import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.business.Service;
import com.anhndt.audiobook.entity.ItemEntity;
import com.anhndt.audiobook.parser.WebServicesParser;
import com.anhndt.audiobook.utils.DBUtil;
import com.anhndt.audiobook.utils.DialogUtil;
import com.anhndt.audiobook.utils.StringUtil;
import com.anhndt.audiobook.utils.Util;
import com.sun.lwuit.Button;
import com.sun.lwuit.CheckBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Container;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import org.ksoap2.serialization.SoapObject;

/**
 *
 * @author Loki
 */
public final class LoginForm extends Form implements ActionListener {

    Button mButtonLogin = new Button(Resource.CMD_LOGIN);
    Button mButtonRegister = new Button(Resource.CMD_REGISTER);
    Button mFogotPasswd = new Button(Resource.CMD_FORGOT_PASSWD);
    CheckBox mRememberMe = new CheckBox(Resource.CMD_REMEMBER);
    CheckBox mAutoLogin = new CheckBox(Resource.CMD_AUTO_LOGIN);
    TextField mUserName = new TextField(DBUtil.getValue(DBUtil.DB_RECORD_USER_NAME));
    TextField mPasswd = new TextField(DBUtil.getValue(DBUtil.DB_RECORD_PASSWD));
//    TextField txtPhoneNumber = new TextField("01649593518");
//    TextField txtPasswd = new TextField("a");
    Command mCommanExit = new Command(Resource.CMD_EXIT);
    Command mCommanLogin = new Command(Resource.CMD_LOGIN);

    public LoginForm(BaseForm currentForm) {
        super(Resource.CMD_LOGIN);
        currentForm = null;
        Display.getInstance().setThirdSoftButton(false);
        setSelectCommandText("");
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        mUserName.setConstraint(TextField.ANY);
        mUserName.setInputMode("abc");
        mUserName.setHint(Resource.TXT_USER_NAME);
        mUserName.setPaintInputType(false);
        mPasswd.setConstraint(TextField.PASSWORD);
        mPasswd.setInputMode("abc");
        mPasswd.setHint(Resource.TXT_PASSWD);
        mPasswd.setPaintInputType(false);
        //tét
//        mUserName.setText("anhndt");
//        mPasswd.setText("12345678");

        mButtonLogin.setAlignment(Button.CENTER);
        mButtonLogin.setPressedStyle(mButtonLogin.getSelectedStyle());
        mButtonRegister.setAlignment(Button.CENTER);
        mButtonRegister.setPressedStyle(mButtonRegister.getSelectedStyle());
        mFogotPasswd.setUIID("Link");
        mFogotPasswd.addActionListener(this);
        mButtonLogin.addActionListener(this);
        mButtonRegister.addActionListener(this);

        mRememberMe.setSelected(DBUtil.getValue(DBUtil.DB_RECORD_REMEMBER_ACCOUNT, Resource.TXT_YES).equals(Resource.TXT_YES));
        mAutoLogin.setSelected(DBUtil.getValue(DBUtil.DB_RECORD_AUTO_LOGIN, Resource.TXT_NO).equals(Resource.TXT_YES));
        addComponent();
    }

    void addComponent() {
        int paddingMarginLeft = mButtonLogin.getUnselectedStyle().getPadding(LEFT) + mButtonLogin.getUnselectedStyle().getMargin(RIGHT);
        //Panel Account
        Label lblAccountName = new Label(Resource.TXT_ACCOUNT);
        Label lblPasswd = new Label(Resource.TXT_PASSWD);
        lblPasswd.getUnselectedStyle().setMargin(TOP, 8);
        Container panelCaption = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        panelCaption.addComponent(lblAccountName);
        panelCaption.addComponent(lblPasswd);
        //panelCaption.getUnselectedStyle().setMargin(RIGHT, Display.getInstance().getDisplayWidth() / 10);

        Container panelText = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        panelText.addComponent(mUserName);
        panelText.addComponent(mPasswd);
        panelText.addComponent(mRememberMe);
        panelText.addComponent(mAutoLogin);
        panelText.addComponent(mFogotPasswd);

        if (Display.getInstance().getDisplayWidth() >= 320) {
            panelCaption.getUnselectedStyle().setMargin(LEFT, paddingMarginLeft);
            panelText.getUnselectedStyle().setMargin(RIGHT, paddingMarginLeft);
        }

        Container panelAcc = new Container(new BorderLayout());
        panelAcc.addComponent(BorderLayout.WEST, panelCaption);
        panelAcc.addComponent(BorderLayout.CENTER, panelText);

        addComponent(panelAcc);
        addComponent(mButtonLogin);
        addComponent(mButtonRegister);
        addCommand(mCommanExit);
        addCommand(mCommanLogin);
        setBackCommand(mCommanExit);
        addCommandListener(this);
    }

    protected void onShowCompleted() {
        if (mAutoLogin.isSelected() && !StringUtil.isNullOrEmpty(mPasswd.getText()) && !StringUtil.isNullOrEmpty(mUserName.getText())) {
            System.out.println("onShowCompleted");
            login();
        }
    }

    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == mFogotPasswd) {
            forgotPasswd();
        } else if (evt.getSource() == mButtonRegister) {
            register();
        } else if (evt.getSource() == mButtonLogin || evt.getCommand() == mCommanLogin) {
            login();
        } else if (evt.getCommand() == mCommanExit) {
            AudioStore.exitApp(false);
        }
    }

    void forgotPasswd() {
        //show ForgotPasswrdForm
        ForgotPasswordForm form = new ForgotPasswordForm(this);
        form.show();
    }

    void register() {
        //show form register
        RegisterForm form = new RegisterForm(this);
        form.show();
    }
    public static boolean validateAccount(String mobile, String passwd) {
        //3 is min passwd lenght
        //24 is max passwd lenght
        return (!StringUtil.isNullOrEmpty(mobile) && !StringUtil.isNullOrEmpty(passwd));
    }

    void login() {
        System.out.println("Login");
        if (!validateAccount(mUserName.getText(), mPasswd.getText())) {
            DialogUtil.showErrorDialog(Resource.TXT_WARRING_VALIDATE_ACCOUNT);
            return;
        }
        //Check TextUser  + TextPasswd
        Thread t = new Thread() {

            public void run() {

                try {
                    AccountService mAccountService = new AccountService();
                    String message = mAccountService.doLogin(mUserName.getText(), mPasswd.getText());
                    System.out.println("UserID : " + Util.userID);
                    if (Util.userID != null && !Util.userID.equals("0")) {
                        //Login Successful
                        //Save User + pass into RMS

                        Util.username = mUserName.getText();
                        Util.passwd = mPasswd.getText();
                        if (mRememberMe.isSelected()) {
                            rememberMe();
                        } else {
                            unRememberMe();
                        }
                        DBUtil.changeValue(DBUtil.DB_RECORD_AUTO_LOGIN, mAutoLogin.isSelected() ? Resource.TXT_YES : Resource.TXT_NO);
                        DBUtil.changeValue(DBUtil.DB_RECORD_REMEMBER_ACCOUNT, mRememberMe.isSelected() ? Resource.TXT_YES : Resource.TXT_NO);
                        DBUtil.changeValue(DBUtil.DB_RECORD_HAVE_ACCOUNT, Resource.TXT_YES);
                        Indicator.hide();
                        //Load Config
                        //Show MainForm
//                        Indicator.hide();
                        new MainForm().show();
//                        new TestMediaPlayerForm();
                    } else {
                        //Login Failed
//                        Indicator.hide();
                        DialogUtil.showInfoDialog(message);
                        Indicator.hide();
                    }
                } catch (Exception ex) {
                    System.out.println("***************************Faild service Login");
                    ex.printStackTrace();
                    DialogUtil.showErrorConnectServer();
                    Indicator.hide();
//                    DialogUtil.showInfoDialog(Resource.LOGIN_FAILED);
                } finally {
                }
            }
        };
        t.setPriority(Thread.MAX_PRIORITY);
        Indicator.show(Resource.LOGING_MESSAGE, t);
    }

    void rememberMe() {
        DBUtil.changeValue(DBUtil.DB_RECORD_USER_NAME, Util.username);
        DBUtil.changeValue(DBUtil.DB_RECORD_PASSWD, Util.passwd);
    }

    void unRememberMe() {
        DBUtil.delete(DBUtil.DB_RECORD_USER_NAME);
        DBUtil.delete(DBUtil.DB_RECORD_PASSWD);
    }

    class AccountService {

        final String USER_ID = "i";
        final String MESSAGE = "msg";
        private WebServicesParser parser;
        Service service;

        void LoginParser() {
        }

        public String doLogin(String username, String passwd) throws Exception {
            service = new Service(Service.METHOD_LOGIN);
            service.addProperty("u", username);
            service.addProperty("p1", passwd);
            service.addProperty("y", "" + ItemEntity.TYPE_USER_LOGIN);

            parser = new WebServicesParser(service);

            //call service
            SoapObject response = parser.getResponse();
            System.out.println("[LicenceParser] response = " + response);
            String message = "";
            if (response != null) {
                SoapObject soap = (SoapObject) response.getProperty(0);

                message = parser.getProperty(soap, MESSAGE);
                String userID = parser.getProperty(soap, USER_ID);
                if (!StringUtil.isNullOrEmpty(userID)) {
                    Util.userID = userID;
                }

                Util.DO_LOGIN = true;
            }
            return message;
        }
    }
}
